package cn.chinaflame.pagodas.utils.email;

import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import cn.chinaflame.pagodas.entity.PaEmailLog;
import cn.chinaflame.pagodas.service.PaEmailLogService;

/**
 * 发送邮件辅助类
 * 
 * @author pengcheng.zhao
 * @version $Id: MailUtil.java, 
 */

@Component
public final class EmailService {
	 private static final Logger log = LoggerFactory.getLogger(EmailService.class);
	@Autowired
	private PaEmailLogService paEmailLogService;
	private EmailService() {
	}
	/**
	 * 发送邮件
	 */
	public final boolean sendEmail(Email email) {
		log.info("sendEmail:email:{}",email);
		// 初始化邮件引擎
		EmailSender sender = new EmailSender(email);
//		sender.setNamePass(email.getName(), email.getPassword(), email.getKey());
		if (!sender.setFrom(email.getFrom()))
			return false;
		if (!sender.setTo(email.getSendTo()))
			return false;
		if (email.getCopyTo() != null && sender.setCopyTo(email.getCopyTo()) == false)
			return false;
		if (!sender.setSubject(email.getTopic()))
			return false;
		if (!sender.setBody(email.getBody()))
			return false;
		if (email.getFileAffix() != null) {
			for (int i = 0; i < email.getFileAffix().length; i++) {
				if (!sender.addFileAffix(email.getFileAffix()[i]))
					return false;
			}
		}
		boolean result = sender.sendout(email);// 发送
		String attachFile = String.join(",", email.getFileAffix());
		PaEmailLog logg  = new PaEmailLog(email.getSendTo(),email.getTopic(),email.getBody(),email.getCopyTo(),result?email.getSendSucc():email.getSendErr(),attachFile);
		paEmailLogService. addEmail(logg);
		log.info("logg:{},result:{}",logg,result);
		return result;
	}
	 
}
